//
//  CalculationTopic.swift
//  XingCeHelper
//
//  Created by 申铭 on 2022/7/27.
//

import UIKit

enum Symbol: String {
    case add = "+"
    case sub = "-"
    case multiply = "*"
    case division = "÷"
    
    case restart = "重来"
}

class CalculationTopic: BaseTopic {
    var num1: Int = 0
    var num2: Int = 0
    var symbol: Symbol = .add
    
    var inputAnswer: Float?
    var answer: Float = 0
    
    override func setInputAnswer(answer: String?, numerator: Float = 0.0, denominator: Float = 1) {
        inputAnswer = Float(answer ?? "")
    }
    
    // LaTex公式
    override func getTopicDesc() -> String {
        if symbol == .multiply {
            return "\(num1) \\times \(num2) =\\; ?"
        } else if symbol == .division {
            return "\(num1) {\\div} \(num2) =\\; ?"
        }
        return "\(num1) \(symbol.rawValue) \(num2) =\\; ?"
    }
    
    override func answerIsCorrect() -> Bool {
        guard let inputAnswer = inputAnswer else { return false }
        
        switch symbol {
        case .add:
            answer = Float(num1 + num2)
            return answer == inputAnswer
        case .sub:
            answer = Float(num1 - num2)
            return answer == inputAnswer
        case .multiply:
            answer = Float(num1 * num2)
            return answer == inputAnswer
        case .division:
            answer = Float(num1) / Float(num2)
            return abs(answer - inputAnswer) < 0.4
        default: return false
        }
    }
    
    override func getResultDesc() -> NSMutableAttributedString {
        var sym = "√"
        var color = UIColor.black
        if !answerIsCorrect() {
            sym = "×"
            color = .red
        }
        let input = (inputAnswer == nil ? "空" : formatNum(inputAnswer ?? 0))
        let str = "\(num1) \(symbol.rawValue) \(num2) = \(formatNum(answer)) (\(input)) \(sym)"
        
        let attri = NSMutableAttributedString(string: str, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 18)])
        let tmpRange = NSRange(location: str.count - 1, length: 1)
        
        attri.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: tmpRange)
        return attri
    }
    
    private func formatNum(_ answer: Float) -> String {
        switch symbol {
        case .add, .sub, .multiply: return String(format: "%.0f", answer)
        case .division: return String(format: "%.2f", answer)
        default: return String(format: "%.0f", answer)
        }
    }
}
